<template>
  <div class="main">
    <div v-if="!isOpen" @mouseover="toogle" @click="toogle">
      <div class="toc-sidebar-btn toc-sidebar-btn-right">
        <el-button v-if="place==='rtl'" icon="el-icon-arrow-left" circle type="primary"></el-button>
      </div>
      <div class="toc-sidebar-btn toc-sidebar-btn-left">
        <el-button v-if="place==='ltr'" icon="el-icon-arrow-right" circle type="primary"></el-button>
      </div>
    </div>

    <el-drawer
      :visible.sync="isOpen"
      :title="title"
      :modal="false"
      :direction="place"
      :wrapperClosable="true"
      :modal-append-to-body="false"
      :size="'20%'"
    >
      <el-tree :data="tree" @node-click="navigation"></el-tree>
    </el-drawer>
  </div>
</template>

<script>
import "element-ui/lib/theme-chalk/index.css";
export default {
  name: "SideBar",
  data() {
    return {
      container: document, //文章容器
      title: document.title,
      lastUrl: "",
      isOpen: false,
      place: "rtl", //目录位置，值有rtl / ltr / ttb / btt
      tree: [], //目录数据
      urlConfig: []
    };
  },
  methods: {
    toogle() {
      this.isOpen = this.isOpen ? false : true;
      if (this.isOpen) {
        this.refresh();
      }
    },
    refresh() {
      if (document.location.href.split("#")[0] != this.lastUrl) {
        this.lastUrl = document.location.href.split("#")[0];
        this.title = document.title;
        this.tree = this.getComponentData().children;
        this.$message({
          message: "目录生成成功",
          type: "success"
        });
      }
    },
    changePos() {
      if (this.place === "right") {
        this.place = "left";
      } else {
        this.place = "right";
      }
    },
    navigation(node) {
      window.location.href = node.href;
    },
    extractHeadings() {
      //获取页面上所有H1-H6的元素
      let headTagList = [];
      for (let i = 1; i <= 6; i++) {
        headTagList.push("h" + i);
      }
      this.container.querySelectorAll(headTagList).forEach(element => {
        if (!element.querySelector("a[name=toc-anchor]")) {
          //添加锚点
          let anchor = document.createElement("a");
          anchor.id = element.innerText;
          anchor.name = "toc-anchor";
          anchor.href = "#" + element.innerText;
          element.appendChild(anchor);
          // element.parentElement.insertBefore(anchor,element)
        }
      });
      let headAnchorList = [];
      for (let i = 1; i <= 6; i++) {
        headAnchorList.push("h" + i + ">" + "a[name=toc-anchor]");
        // headTagList.push("h" + i);
      }
      let headCssSelectors = headAnchorList.join();
      return this.container.querySelectorAll(headCssSelectors);
    },
    buildTOCTree(heads) {
      let tree = {
        label: "github-md-toc",
        expand: true,
        children: [],
        parent: null,
        tag: "A",
        href: ""
      };
      let pre = tree;
      for (let i = 0; i < heads.length; i++) {
        let tagName = heads[i].parentNode.tagName;
        if (tagName <= pre.tag) {
          while (tagName <= pre.tag) {
            pre = pre.parent;
          }
        }
        pre.children.push({
          label: heads[i].parentNode.textContent,
          expand: true,
          children: [],
          parent: pre,
          tag: tagName,
          href: heads[i].href,
          offset: heads[i].offsetTop
        });
        pre = pre.children[pre.children.length - 1];
      }
      return tree;
    },
    getComponentData() {
      this.urlConfig.forEach(element => {
        if (window.location.host == element.host) {
          this.container = document.querySelector(element.selector);
        }
      });
      let heads = this.extractHeadings();
      let data = this.buildTOCTree(heads);
      return data;
    }
  },
  mounted: function() {
    this.$message({ 
      message: "目录注入成功",
      type: "success"
    });
    document.ondblclick = () => {
      this.refresh();
    };
    //加载设置
    window.chrome.storage.sync.get(null, data => {
      if (data && data.urlConfig && data.urlConfig.length > 0) {
        this.isOpen = data.autOpen;
        this.place = data.position;
        this.urlConfig = data.urlConfig;
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  z-index: 99999 !important;
}
.main {
  .drawer-left {
    margin-left: 0%;
  }
  .drawer-right {
    margin-left: 80%;
  }
  .toc-sidebar-btn {
    position: fixed;
    top: 48%;
    height: 35px;
    width: 35px;
    z-index: 9999;
    cursor: pointer;
    border: none;
  }

  .toc-sidebar-btn-right {
    right: 18px;
  }
  .toc-sidebar-btn-left {
    left: 18px;
  }
}
</style>